import express = require("express");

import { initDB } from "../db";
import { editTags } from "./tags";
import { debug } from "../utils/log";
import { COL_MEDIA } from "../db/config";
import { Message } from "../utils/message";
import { storeCacheByKey } from "../db/cache";

export async function editTitle(key: string, title: string) {
	const db = await initDB();
	const mp3 = db.collection(COL_MEDIA);
	await mp3.updateOne({ key }, { $set: { title } });
}

export async function routerEditTitle(
	res: express.Response,
	key: string,
	title: string
) {
	try {
		debug({ url: "/edit", key, title });
		await editTitle(String(key), String(title));
	} catch (error) {
		debug({
			url: "/edit",
			key: String(key),
			error,
		});

		return res.send(
			Message.err("EDIT_TITLE_ERR", 404, {
				info: error,
			})
		);
	}

	storeCacheByKey(key);

	return res.send(
		Message.success({
			info: "EDIT_TITLE_SUCCESS",
		})
	);
}

export async function routerEditTags(
	res: express.Response,
	key: string,
	tags: string
) {
	try {
		const arrTags: string[] =
			typeof tags === "string" ? JSON.parse(tags) : tags;

		debug({ url: "/edit", key, tags: arrTags });
		await editTags(String(key), arrTags);
	} catch (err) {
		debug({
			url: "/edit",
			key: String(key),
			error: err,
		});
		return res.send(
			Message.err("TAG_EDIT_ERR", 404, {
				info: String(err),
			})
		);
	}

	storeCacheByKey(key);
	return res.send(
		Message.success({
			info: "EDIT_TAG_SUCCESS",
		})
	);
}
